home *** CD-ROM | disk | FTP | other *** search
- From: bxiao@msn.com (Bing Xiao)
- Subject: modifying a 'const' variable, a bug in VC++?
- Date: 25 Feb 96 06:54:20 -0800
- Message-ID: <00001a81+0000a7f1@msn.com>
- Path: news.msn.com!msn.com
- Newsgroups: comp.lang.c++
- Organization: The Microsoft Network (msn.com)
-
- Although modifying a 'const' is not desired(and should
- be prohibited), the following code should be able to do
- that:
-
- main()
- {
- const int i = 1;
- int* j = (int *)&i; // cast a "const int*" to "int*". The
- // compiler should allow it
-
- *j = 2;
- cout << *j << newl; // should print "2"
- cout << i << newl; // should print "2" too
- }
-
- when i compile the program in VC++ 4.0, it compiles without any problem.
- However, when it runs, the result is:
- 2
- 1
-
- When I run in debugger, I took a step-by-step watch to variable "i".
- before the last statement is executed, "i" has a value "2", however,
- when the left "<<" operator was executed(I mean the one in "cout << i")
- the actual parameter value passed to iostream::operator<<(int) is 1.
- That means, it actually execute iostream::operator<<(1).
-
- I consider this a bug in VC++(The correct result should be 2\n2\n.
- Any comments? I just want to get the concept of "const" clarified.
- Thanks.
-